package com.miplus.ccrm.core.service.crd;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.miplus.ccrm.common.CmdResVo;
import com.miplus.ccrm.common.JPubUtils;
import com.miplus.ccrm.common.JSysUser;
import com.miplus.ccrm.common.JUsrPerm;
import com.miplus.ccrm.core.controller.vo.credit.FiTaskResVo;
import com.miplus.ccrm.core.controller.vo.credit.LoanRepayReqVo;
import com.miplus.ccrm.core.controller.vo.credit.LoanRepayResVo;
import com.miplus.ccrm.core.mapper.AiListMapper;
import com.miplus.ccrm.core.mapper.FiTaskOldhistMapper;
import com.miplus.ccrm.core.pojo.*;
import com.miplus.ccrm.core.mapper.IouRepaySerialMapper;
import com.miplus.ccrm.core.service.ExportService;
import com.miplus.ccrm.core.service.conf.SysNamesService;
import com.miplus.ccrm.core.utils.EnumFiCaseStatus;
import com.miplus.ccrm.core.utils.EnumGrpType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

/**
* @author wangzl
* @description 针对表【iou_repay_serial(还款流水(业务表))】的数据库操作Service实现
* @createDate 2024-11-07 13:42:07
*/
@Service
public class IouRepaySerialServiceImpl extends MPJBaseServiceImpl<IouRepaySerialMapper, IouRepaySerial>
    implements IouRepaySerialService{
    @Resource
    private FiCreditcasesHistService fiCreditcasesHistService;

    @Resource
    private FiImportHistService fiImportHistService;

    @Resource
    private ExportService exportService;
    @Override
    public IPage<LoanRepayResVo> selectRepaidList(JSysUser sysUser, LoanRepayReqVo paras)
    {
        String $usrid=sysUser.getUsrid();
        //String usrgrp=sysUser.getGroups();
        //SysGrp grp = sysGrpService.getById(usrgrp);
        //if( grp.getType() == EnumGrpType.TEAM.value)
        //    usrgrp = grp.getParentid();
        //2024-08-18 add and fh.distdt=fc.distdt 条件及fi.repay
        boolean viewAllCase= JUsrPerm.viewAllFiCase(sysUser);
        boolean viewGrpFiCase = false;
        if(!viewAllCase && sysUser.getMgrgrplist().size()>0)
            viewGrpFiCase = true;
        return selectJoinListPage(new Page<>(paras.getPageNum(),paras.getPageSize()),
                LoanRepayResVo.class,
                new MPJLambdaWrapper<IouRepaySerial>()
                        .leftJoin(FiCreditcases.class, "fc", FiCreditcases::getCreditcaseid, IouRepaySerial::getCreditcaseid)
                        .leftJoin(FiCreditcasesHist.class,"fdh",FiCreditcasesHist::getHistid,IouRepaySerial::getDisthistid)
                        .leftJoin(" fi_creditcases_hist frh on frh.creditcaseid = fdh.creditcaseid and frh.distbatchid = fdh.distbatchid and frh.actiontype=3")
                        .leftJoin(" iou_product iup on iup.product_id = fc.product_id and ifnull(iup.merchant_id,'')=ifnull(fc.merchant_id,'')")
                        .in(viewGrpFiCase,IouRepaySerial::getSendtodept,sysUser.getMgrgrplist())
                        .eq(!viewAllCase && !viewGrpFiCase,IouRepaySerial::getSendtousr,$usrid)

                        .eq(JPubUtils.IsNotEmpty(paras.getLoanInvoiceId()),IouRepaySerial::getLoanInvoiceId,paras.getLoanInvoiceId())
                        .eq(JPubUtils.IsNotEmpty(paras.getCreditcaseid()),IouRepaySerial::getCreditcaseid,paras.getCreditcaseid())
                        .eq(JPubUtils.IsNotEmpty(paras.getCustomernumber()),IouRepaySerial::getBorrowerId,paras.getCustomernumber())

                        .in(ObjectUtils.isNotNull(paras.getDeptlist()),IouRepaySerial::getSendtodept,paras.getDeptlist())
                        .in(ObjectUtils.isNotNull(paras.getSendtousrlist()),IouRepaySerial::getSendtousr,paras.getSendtousrlist())

                        .in(ObjectUtils.isNotNull(paras.getDisttaglist()),FiCreditcasesHist::getDisttag,paras.getDisttaglist())

                        .in(ObjectUtils.isNotNull(paras.getProductlist()),"iup.id",paras.getProductlist())


                        .ge(ObjectUtils.isNotNull(paras.getCpstarttime1()),FiCreditcasesHist::getCpStartTime,paras.getCpstarttime1())
                        .le(ObjectUtils.isNotNull(paras.getCpstarttime2()),FiCreditcasesHist::getCpStartTime,paras.getCpstarttime2())

                        .ge(ObjectUtils.isNotNull(paras.getCpendtime1()),FiCreditcasesHist::getCpEndTime,paras.getCpendtime1())
                        .le(ObjectUtils.isNotNull(paras.getCpendtime2()),FiCreditcasesHist::getCpEndTime,paras.getCpendtime2())

                        .ge(ObjectUtils.isNotNull(paras.getTradetime1()),IouRepaySerial::getTradeTime,paras.getTradetime1())
                        .le(ObjectUtils.isNotNull(paras.getTradetime2()),IouRepaySerial::getTradeTime,paras.getTradetime2())

                        .ge(ObjectUtils.isNotNull(paras.getRepayamt1()),IouRepaySerial::getRepayAmt,paras.getRepayamt1())
                        .le(ObjectUtils.isNotNull(paras.getRepayamt2()),IouRepaySerial::getRepayAmt,paras.getRepayamt2())


                        .ge(ObjectUtils.isNotNull(paras.getMthsday1()),FiCreditcasesHist::getCpOverdueDays,paras.getMthsday1())
                        .le(ObjectUtils.isNotNull(paras.getMthsday2()),FiCreditcasesHist::getCpOverdueDays,paras.getMthsday2())
                        .selectAll(IouRepaySerial.class)
                        .selectAs(FiCreditcasesHist::getCpTotalamt,LoanRepayResVo::getCpTotalAmt)
                        .selectAs(FiCreditcasesHist::getCpStartTime,LoanRepayResVo::getCpStartTime)
                        .selectAs(FiCreditcasesHist::getCpEndTime,LoanRepayResVo::getCpEndTime)
                        .selectAs(FiCreditcasesHist::getCpOverdueDays,LoanRepayResVo::getCpOverdueDays)

                        .selectAs("iup.product_id",LoanRepayResVo::getProductId)
                        .selectAs("iup.product_name",LoanRepayResVo::getProductName)

                        .selectAs("iup.merchant_id",LoanRepayResVo::getMerchantId)
                        .selectAs("iup.merchant_name",LoanRepayResVo::getMerchantName)
                        .selectAs(FiCreditcasesHist::getDisttag,LoanRepayResVo::getDisttag)
                        .selectAs(FiCreditcasesHist::getDistbatchid,LoanRepayResVo::getDistbatchid)
                        .selectAs("frh.recycledt", LoanRepayResVo::getRecycledt)
                        .orderByDesc(IouRepaySerial::getTradeTime)  //还款时间降序+客户号升序+案件编号升序+借据号升序排列
                        .orderByAsc(IouRepaySerial::getBorrowerId)
                        .orderByAsc(IouRepaySerial::getCreditcaseid)
                        .orderByAsc(IouRepaySerial::getLoanInvoiceId)
        ).convert(x->{
            if(ObjectUtils.isNotNull(x.getCpOverdueDays()))
                x.setOverdueStage(JPubUtils.calculateOverdueStage(x.getCpOverdueDays()));
            /**
             * 还款操作类型：1-逾期还款、2-正常还款、3-提前还款、4-代偿还款、5-随借随还还款、6-逾期随借随还还款、7-代扣
             */
            if(StringUtils.isEmpty(x.getRepayOprtatorTpye()))
                x.setRepayOprtatorTpyeDesc(null);
            else if(x.getRepayOprtatorTpye().equals("1"))
                x.setRepayOprtatorTpyeDesc("逾期还款");
            else if(x.getRepayOprtatorTpye().equals("2"))
                x.setRepayOprtatorTpyeDesc("正常还款");
            else if(x.getRepayOprtatorTpye().equals("3"))
                x.setRepayOprtatorTpyeDesc("提前还款");
            else if(x.getRepayOprtatorTpye().equals("4"))
                x.setRepayOprtatorTpyeDesc("代偿还款");
            else if(x.getRepayOprtatorTpye().equals("5"))
                x.setRepayOprtatorTpyeDesc("随借随还还款");
            else if(x.getRepayOprtatorTpye().equals("6"))
                x.setRepayOprtatorTpyeDesc("逾期随借随还还款");
            else if(x.getRepayOprtatorTpye().equals("7"))
                x.setRepayOprtatorTpyeDesc("代扣");

            return x;
        });
    }
    @Override
    public IPage<IouRepaySerial> getRepaidList(LoanRepayReqVo paras)
    {
        return selectJoinListPage(new Page<>(paras.getPageNum(),paras.getPageSize()),
                IouRepaySerial.class,
                new MPJLambdaWrapper<IouRepaySerial>()
                        .leftJoin(IouLoanInvoiceInfo.class,"ili",IouLoanInvoiceInfo::getLoanInvoiceId,IouRepaySerial::getLoanInvoiceId)
                        // .leftJoin(FiCreditcases.class,"fc",FiCreditcases::getCreditcaseid,IouLoanInvoiceInfo::getCreditcaseid)
                        .eq(JPubUtils.IsNotEmpty(paras.getLoanInvoiceId()),IouRepaySerial::getLoanInvoiceId,paras.getLoanInvoiceId())
                        .eq(JPubUtils.IsNotEmpty(paras.getCreditcaseid()),IouLoanInvoiceInfo::getCreditcaseid,paras.getCreditcaseid())
                        .selectAll(IouRepaySerial.class)
                        .orderByDesc(IouRepaySerial::getTradeTime)
                        .orderByAsc(IouRepaySerial::getLoanInvoiceId)
        );
    }
    @Override
    public CmdResVo updateRapySerial(String usrid, IouRepaySerial iouRepaySerial)
    {
        if(iouRepaySerial == null || StringUtils.isEmpty(iouRepaySerial.getDetailNo()))
        {
            return new CmdResVo(-1,"参数不正确,没有指定还款记录");
        }

        IouRepaySerial repaySerial = getById(iouRepaySerial.getDetailNo());
        if( repaySerial == null)
            return new CmdResVo(-1,"没有找到还款记录 detailno:"+iouRepaySerial.getDetailNo());
        if(ObjectUtils.isNotNull(iouRepaySerial.getDisthistid()))
        {
            FiCreditcasesHist fiCreditcasesHist = fiCreditcasesHistService.getById(iouRepaySerial.getDisthistid());
            if (fiCreditcasesHist == null)
                return new CmdResVo(-1, "没有找到对于的分案派工明细记录.");
            else {
                repaySerial.setDisthistid(fiCreditcasesHist.getHistid());
                repaySerial.setCreditcaseid(fiCreditcasesHist.getCreditcaseid());
                repaySerial.setSendtodept(fiCreditcasesHist.getSendtodept());
                repaySerial.setSendtousr(null);
                if(fiCreditcasesHist.getStatus().equals(EnumFiCaseStatus.Assign.value))
                {
                    repaySerial.setAssignhistid(fiCreditcasesHist.getHistid());
                    repaySerial.setSendtousr(fiCreditcasesHist.getSendtousr());
                }
            }
        }
        if(ObjectUtils.isNotNull(iouRepaySerial.getConfirmRepaid()))
            repaySerial.setConfirmRepaid(iouRepaySerial.getConfirmRepaid());
        repaySerial.setConfirmusr(usrid);
        repaySerial.setConfirmdt(new Date());
        repaySerial.setStatus(2);
        baseMapper.update(null,new UpdateWrapper<IouRepaySerial>()
                .lambda()
                .eq(IouRepaySerial::getDetailNo,repaySerial.getDetailNo())
                .set(IouRepaySerial::getDisthistid,repaySerial.getDisthistid())
                .set(IouRepaySerial::getAssignhistid,repaySerial.getAssignhistid())
                .set(IouRepaySerial::getSendtodept,repaySerial.getSendtodept())
                .set(IouRepaySerial::getSendtousr,repaySerial.getSendtousr())
                .set(IouRepaySerial::getCreditcaseid,repaySerial.getCreditcaseid())
                .set(IouRepaySerial::getConfirmusr,repaySerial.getConfirmusr())
                .set(IouRepaySerial::getConfirmdt,repaySerial.getConfirmdt())
                .set(IouRepaySerial::getConfirmRepaid,repaySerial.getConfirmRepaid())
                .set(IouRepaySerial::getStatus,repaySerial.getStatus())
        );
        return new CmdResVo(1,"更新成功");
    }

    @Override
    public CmdResVo expRepaidList(JSysUser sysUser, LoanRepayReqVo paras, HttpServletResponse response)
    {
        String $usrid=sysUser.getUsrid();
        IPage<LoanRepayResVo> pages=selectRepaidList(sysUser, paras);
        ArrayList arr=new ArrayList();

        String exptempid=JPubUtils.getExpTempID(paras.getExpfilename(),"还款明细列表");
        String filename=JPubUtils.getExpFileName(
                paras.getExpfilename(),exptempid
        );
        pages.convert(u->{
            HashMap map=JPubUtils.toExportMap(u);
            if(map!=null) arr.add(map);
            return u;
        });
        CmdResVo resVo=exportService.ToExcel(
                response,
                arr,
                paras.getExpidlist(),
                paras.getExpnamelist(),
                filename,
                $usrid
        );

        int okcount=resVo.getCount();
        if(okcount>0){
            fiImportHistService.AddExportHist(
                    resVo.getKeyId(),
                    $usrid,
                    exptempid,
                    filename,
                    okcount
            );
        }

        return resVo;
    }
}





